package org.pybaldaj;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

public class RectangularField implements IField {

	private static final byte DEFAULT_SIZE = 5;
	
	private ArrayList<ICell> cells;
	private byte rowCount = DEFAULT_SIZE;
	private byte colCount = DEFAULT_SIZE;
	
	public RectangularField() {
		super();
		cells = new ArrayList<ICell>(rowCount*colCount);
		for (int i = 0; i < rowCount*colCount; ++i) {
			cells.add(new DefaultCell(this, i));
		}
	}

	private class Coords {
		public byte x;
		public byte y;
		public Coords(byte x, byte y) {
			super();
			this.x = x;
			this.y = y;
		}
	}
	
	private int convertCoordsToId(Coords c) {
		return c.y * colCount + c.x; 
	}
	
	private Coords convertIdToCoords(int cellId) {
		return new Coords(
				(byte) (cellId % rowCount),
				(byte) (cellId / rowCount));
	}

	public Collection<ICell> getCellNeighbours(ICell cell) {
		// FIXME null
		Collection<ICell> res = new LinkedList<ICell>();
		
		Coords c = convertIdToCoords(cell.getId());
		
		if (c.x > 0) {
			res.add(getCell(convertCoordsToId(new Coords((byte) (c.x - 1), c.y))));
		}
		if (c.x < colCount - 1) {
			res.add(getCell(convertCoordsToId(new Coords((byte) (c.x + 1), c.y))));
		}
		if (c.y > 0) {
			res.add(getCell(convertCoordsToId(new Coords(c.x, (byte) (c.y - 1)))));
		}
		if (c.y < rowCount - 1) {
			res.add(getCell(convertCoordsToId(new Coords(c.x, (byte) (c.y + 1)))));
		}
		
		return res;
	}

	public List<ICell> getCells() {
		
		return cells;
	}

	public ICell getCell(int cellId) {
		return cells.get(cellId);
	}
}
